
import pika
from rabbitmq_send.setting import *

# 测试事务
def test_tx():
    # 添加用户名和密码
    credentials = pika.PlainCredentials(USERNAME, PASSWD)
    # 配置连接参数
    parameters = pika.ConnectionParameters(host=HOST, credentials=credentials)
    # 创建一个连接对象
    connection = pika.BlockingConnection(parameters)
    # 创建一个信道
    channel = connection.channel()
    # 声明队列
    channel.queue_declare(queue='test', durable=True)
    # 开启事务
    a = channel.tx_select()
    print(a)
    try:
        channel.basic_publish(exchange='',
                              routing_key='test',
                              body='hello-world')
        b = channel.tx_commit()
        print(b)
    except:
        c = channel.tx_rollback()
        print(c)

# 测试confirm模式
def test_confirm():
    # 添加用户名和密码
    credentials = pika.PlainCredentials(USERNAME, PASSWD)
    # 配置连接参数
    parameters = pika.ConnectionParameters(host=HOST, credentials=credentials)
    # 创建一个连接对象
    connection = pika.BlockingConnection(parameters)
    # 创建一个信道
    channel = connection.channel()
    # 声明队列
    channel.queue_declare(queue='test', durable=True)
    # 打开通道的确认模式
    channel.confirm_delivery()
    for i in range(3):
        result = channel.basic_publish(exchange='',
                              routing_key='test',
                              body='hello-world')
        if result:
            break



def test3():
    # 添加用户名和密码
    credentials = pika.PlainCredentials(USERNAME, PASSWD)
    # 配置连接参数
    parameters = pika.ConnectionParameters(host=HOST, credentials=credentials)
    # 创建一个连接对象
    connection = pika.BlockingConnection(parameters)
    # 创建一个信道
    channel = connection.channel()
    channel.queue_delete()

# 测试交换机的绑定
def test4():
    # 添加用户名和密码
    credentials = pika.PlainCredentials(USERNAME, PASSWD)
    # 配置连接参数
    parameters = pika.ConnectionParameters(host=HOST, credentials=credentials)
    # 创建一个连接对象
    connection = pika.BlockingConnection(parameters)
    # 创建一个信道
    channel = connection.channel()
    # 声明队列
    channel.queue_declare(queue='test1', durable=True)
    channel.queue_declare(queue='test2', durable=True)
    # 声明交换机
    channel.exchange_delete('myname')
    channel.exchange_declare('myname')
    channel.exchange_delete('youname')
    channel.exchange_declare('youname',internal=True)
    # 交换机绑定
    channel.exchange_bind(destination='youname',source='myname',routing_key='ourheart')
    # 队列绑定
    channel.queue_bind(queue='test1',exchange='myname',routing_key='ourheart')
    channel.queue_bind(queue='test2', exchange='youname',routing_key='ourheart')
    channel.basic_publish(exchange='youname',
                          routing_key='ourheart',
                          body='hello-world')
if __name__ == "__main__":
    test3()
    # test2()
    # test4()